package com.swak.mmap;

import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

/**
 * 文件描述.
 * 
 * @author 618lf
 */
@Getter
@Setter
@Accessors(chain = true)
public class MappedFileNaming {

	private final String prefix;
	private final String suffix;
	private final Predicate<String> predicate;
	private final Pattern pattern;

	public MappedFileNaming() {
		this("mps", ".dat");
	}

	public MappedFileNaming(String prefix, String suffix) {
		this.prefix = prefix;
		this.suffix = suffix;
		this.pattern = Pattern.compile(prefix + "(\\d+)" + suffix);
		this.predicate = Pattern.compile(prefix + "(\\d+)" + suffix).asMatchPredicate();
	}

	public boolean match(String name) {
		return this.predicate.test(name);
	}

	public int fileOffset(String name) {
		Matcher matcher = pattern.matcher(name);
		matcher.find();
		return Integer.parseInt(matcher.group(1));
	}

	public String format(String name) {
		return prefix + name + suffix;
	}
}
